<template>
	<div class="content">
		<div class="pageSearchView">
			<!--			<SearchForm v-model="searchParam" :fields="searchFields" :handleSearch="handleSearch" />-->
			<el-form :inline="true" :model="searchParam" class="demo-form-inline">
				<el-form-item label="物料名称">
					<el-input v-model="searchParam.materialName" placeholder="请输入物料名称" clearable
										style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="物料类型">
					<el-input v-model="searchParam.materialType" placeholder="请输入物料类型" clearable
										style="width: 200px"></el-input>
				</el-form-item>
				<el-form-item label="物料属性">
					<el-select v-model="searchParam.materialProperties" filterable clearable style="width: 200px">
						<el-option v-for="item in materialProperData" :key="item.id" :value="item.id"
											 :label="item.name" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" :icon="Search" @click="handleSearch()">查询</el-button>
					<el-button :icon="Refresh" @click="resetSearch()">重置</el-button>
				</el-form-item>
			</el-form>
		</div>
		<div class="pageTableView">
			<div class="pageTableMenuView">
				<div class="pageTableTitle">列表信息
					<el-icon>
						<house-icon />
					</el-icon>
				</div>
				<div class="pageTableButView">
					<el-button :icon="Plus" @click="handleAdd">新建</el-button>
					<!-- 添加列按钮 -->
					<el-button :icon="Plus" @click="showAddColumnDialog = true" type="primary">表头列配置</el-button>
				</div>
			</div>
			<!-- 表格 -->
			<el-table class="pageTableClass" :data="paginatedData" height="calc(100vh - 320px)" border
								:loading="isLoading">
				<el-table-column label="序号" align="center" width="65">
					<template #default="scope"> {{ (paginationParams.current - 1) * paginationParams.pageSize +
					scope.$index + 1 }}
					</template>
				</el-table-column>
				<el-table-column prop="materialName" label="物料名称" min-width="250" align="center" />
				<el-table-column prop="materialNo" label="物料编码" min-width="250" align="center" />
				<!-- <el-table-column prop="materialType" label="物料类型" min-width="200" align="center" /> -->
				<el-table-column prop="materialProperties" label="物料属性" align="center">
					<template #default="scope">
						{{ materialProperData.find(i => i.id == scope.row.materialProperties)?.name }}
					</template>
				</el-table-column>
				<el-table-column prop="oneMaterialWeight" label="物料重量" align="center" />
				<el-table-column prop="basicUnit" label="主单位" align="center" />
				<el-table-column prop="snp" label="SNP" align="center" />
				<!--				<el-table-column prop="conversionUnit" label="副单位" align="center" />-->
				<!-- <el-table-column prop="weightNumConvert" label="重量个数转换比" min-width="150" align="center" /> -->
				<el-table-column prop="version" label="版本号" min-width="150" align="center" />
				<!-- <el-table-column prop="isSize" label="是否版本" min-width="150" align="center">
					<template #default="scope">
						<div v-if="scope.row.isSize">是</div>
						<div v-else>-</div>
					</template>
				</el-table-column> -->
				<!-- 动态列渲染 -->
				<el-table-column v-for="col in columns" :key="col.tableKey" :prop="col.tableKey"
												 :label="col.tableChineseKey" align="center" />
				<el-table-column label="操作" align="center" fixed="right" width="180">
					<template #default="scope">
						<el-button @click="handleEdit(scope.row)" size="small" type="text" :icon="Edit">编辑</el-button>
						<el-button @click="handleDel(scope.row)" type="danger" size="small" plain text :icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="pagePagination">
				<el-pagination background v-model:current-page="paginationParams.current"
											 v-model:page-size="paginationParams.pageSize" layout="total, sizes, prev, pager, next"
											 :total="pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
			</div>
		</div>
		<!-- 弹窗表单 -->
		<el-dialog v-model="showCrud" :title="crudTitle" width="90%" top="3vh">
			<el-form :model="formData" label-width="150px" ref="ruleFormRef" :rules="rules">
				<el-row>
					<el-form-item label="物料名称" required prop="materialName">
						<el-input v-model="formData.materialName" placeholder="请输入物料名称" style="width: 380px" />
					</el-form-item>
					<el-form-item label="物料编码" required prop="materialNo">
						<el-input v-model="formData.materialNo" placeholder="请输入物料编码" style="width: 380px" />
					</el-form-item>
					<!-- <el-form-item label="物料类型" required prop="materialType">
						<el-input v-model="formData.materialType" placeholder="请输入物料类型" style="width: 380px" />
					</el-form-item> -->
					<el-form-item label="物料属性" required prop="materialProperties">
						<el-select v-model="formData.materialProperties" placeholder="请选择物料属性" style="width: 380px"
											 filterable>
							<el-option v-for="(item, index) of materialProperData" :key="index" :label="item.name"
												 :value="item.id" />
						</el-select>
						<!-- <el-input v-model="formData.materialProperties" placeholder="请输入物料属性" style="width: 380px" /> -->
					</el-form-item>
					<el-form-item label="物料重量">
						<el-input-number v-model="formData.oneMaterialWeight" placeholder="请输入物料重量"
														 style="width: 380px" />
					</el-form-item>
					<!-- <el-form-item label="重量个数转换比" required prop="weightNumConvert">
						<el-input v-model="formData.weightNumConvert" placeholder="请输入重量个数转换比" style="width: 380px" />
					</el-form-item> -->
					<el-form-item label="版本号" :required="formData.materialProperties === '0' ? false : true" prop="version">
						<el-input v-model="formData.version" placeholder="请输入版本号" style="width: 380px" />
					</el-form-item>
					<el-form-item label="TF/TP" prop="tfTp">
						<el-select v-model="formData.tfTp" placeholder="请选择TF/TP" style="width: 380px">
							<el-option label="TF" value="TF" />
							<el-option label="TP" value="TP" />
						</el-select>
					</el-form-item>
					<el-form-item label="是否尺寸" prop="isSize">
						<el-select v-model="formData.isSize" placeholder="请选择是否尺寸" style="width: 380px">
							<el-option label="否" :value="false" />
							<el-option label="是" :value="true" />
						</el-select>
					</el-form-item>
					<el-form-item label="Cycle Time">
						<el-input-number v-model="formData.cycleTime" style="width: 350px;margin-right: 10px"
														 :precision="6" />
						min
					</el-form-item>
					<el-form-item label="主单位" required prop="basicUnit">
						<!--							<el-input v-model="formData.basicUnit" placeholder="请输入主单位" style="width: 380px" />-->
						<el-select v-model="formData.basicUnit" placeholder="请选择主单位" style="width: 380px" filterable>
							<el-option v-for="(item, index) of basicUnitList" :key="index" :label="item.label"
												 :value="item.label" />
						</el-select>
					</el-form-item>
					<el-form-item label="SNP">
						<el-input-number v-model="formData.snp" style="width: 380px;"
														 :precision="6" />
					</el-form-item>
					<el-form-item label="安全有效期">
						<el-input-number v-model="formData.safetyDayTime" style="width: 380px"
														 :precision="0" />
					</el-form-item>
					<el-form-item v-for="col in columns" :key="col.tableKey" :label="col.tableChineseKey"
												:prop="col.tableKey">
						<el-input v-model="formData[col.tableKey]" :placeholder="`请输入${col.tableChineseKey}`"
											style="width: 380px" />
					</el-form-item>
				</el-row>
				<el-col :span="18">
					<el-form-item label="质检方案">
						<el-select v-model="formData.qualityPlanIds" placeholder="请选择质检方案" style="width: 892px" multiple
											 filterable>
							<el-option v-for="(item, index) of qualityList" :key="index" :label="item.name"
												 :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>

				<!--					<el-col v-for="(item, index) of deputyData" :key="index" :span="12">-->
				<!--						<el-form-item :label="index + 1 + `. 副单位`-->
				<!--							">-->
				<!--							<el-input v-model="item.name" placeholder="请输入单位名称" style="width: 180px" />-->
				<!--							<el-input-number v-model="item.propCount" placeholder="比例"-->
				<!--								style="width: 140px;margin-left: 20px" />-->
				<!--							<el-button :icon="Plus" text size="small" style="margin-left: 10px" @click="addDeputyData"-->
				<!--								v-if="index == 0"></el-button>-->
				<!--							<el-button :icon="Delete" text type="danger" size="small" style="margin-left: 10px"-->
				<!--								@click="delDeputyData(index)" v-else></el-button>-->
				<!--						</el-form-item>-->
				<!--					</el-col>-->
			</el-form>
			<template v-slot:footer>
				<div class="dialog-footer">
					<el-button @click="showCrud = false">取消</el-button>
					<el-button type="primary" @click="handleSave">保存</el-button>
				</div>
			</template>
		</el-dialog>
		<!-- 动态添加列的对话框 -->
		<el-dialog v-model="showAddColumnDialog" title="管理列信息">
			<!-- 表格增删改查 -->
			<el-button :icon="Plus" @click="showAddColumnDialog2 = true; columnDialogTitle = '新建'" type="primary"
								 style="margin-bottom: 20px;">新建列
			</el-button>
			<el-table :data="columns">
				<el-table-column prop="tableChineseKey" label="列名称" align="center" />
				<el-table-column prop="tableKey" label="列编码" align="center" />
				<el-table-column label="操作" align="center">
					<template #default="scope">
						<el-button @click="editColumn(scope.row, scope.$index)" size="small" icon="Edit">编辑</el-button>
						<el-button @click="deleteColumn(scope.row, scope.$index)" size="small" type="danger"
											 icon="Delete">删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<template #footer>
				<el-button @click="showAddColumnDialog = false">关闭</el-button>
			</template>
		</el-dialog>
		<!-- 动态添加列的对话框 -->
		<el-dialog v-model="showAddColumnDialog2" :title="columnDialogTitle">
			<el-form>
				<el-form-item label="列名称">
					<el-input v-model="newColumn.tableChineseKey" placeholder="请输入列名称" />
				</el-form-item>
				<el-form-item label="列Key">
					<el-input v-model="newColumn.tableKey" placeholder="请输入列Key" />
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="showAddColumnDialog2 = false">取消</el-button>
				<el-button type="primary" @click="addColumn">确定</el-button>
			</template>
		</el-dialog>
	</div>
</template>
<script lang="ts" setup>
import SearchForm from '@/components/SearchForm.vue';
import { useMaterialata } from '@/hooks/baseData/materialMaintenance';
import axiosInstance from '@/utils/http/api';
import { Delete, Edit, Plus, Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus'; // 假设使用 Element Plus
import { computed, ref } from 'vue';

const {
	searchParam,
	paginationParams,
	pageTotal,
	paginatedData,
	searchFields,
	handleSearch,
	handleSizeChange,
	handleCurrentChange,
	addmateriaL,
	deletemateriaL,
	isLoading,
	ruleFormRef,
	rules,
	formData
} = useMaterialata();
onMounted(() => {
	getColumnsList();
});
// 动态列和新列的数据
const columns = ref([
	{ tableChineseKey: '自定义列1', tableKey: 'tableKey', visible: true },
	{ tableChineseKey: '自定义列2', tableKey: 'tableKey', visible: true }
	// 可添加更多默认列
]);

const resetSearch = () => {
	searchParam.value = {}
	paginationParams.current = 1;
	handleSearch();
};

const materialProperData = ref([
	{ name: '采购件', id: '0' },
	{ name: '半成品', id: '1' },
	{ name: '成品件', id: '2' },
	{ name: '模具', id: '3' },
	{ name: '刀具', id: '4' },
	{ name: '备件', id: '5' },
	{ name: '量具', id: '6' },
	{ name: '虚拟件', id: '7' }
]);
const showAddColumnDialog = ref(false);
const showAddColumnDialog2 = ref(false);
const columnDialogTitle = ref('');
const columnIndexNumber = ref(0);
const qualityList = ref([]);
const mainData = ref([{
	name: null,
	popCount: 0
}]);

const deputyData = ref([{
	name: null,
	popCount: 0
}]);


const basicUnitList = ref(
	[{
		label: 'Meter'
	}, {
		label: 'SQ Meter'
	}, {
		label: 'KG'
	}, {
		label: 'EA'
	}, {
		label: 'Hours'
	}, {
		label: 'Dollars'
	}, {
		label: 'PCS'
	}, {
		label: 'Hrs'
	}, {
		label: 'Hour'
	}, {
		label: 'L'
	}, {
		label: 'Gallon'
	}, {
		label: 'Daily'
	}
	]
);

const addDeputyData = () => {
	deputyData.value.push({});
};


const delDeputyData = (e) => {
	deputyData.value.splice(e, 1);
};

const newColumn = ref({
	tableChineseKey: '',
	tableKey: '',
	visible: true,
	id: ''
});
// 查询列
const getColumnsList = () => {
	axiosInstance.post('/api/basedataQualityScheme/getPage', { current: 1, pageSize: 999999 }).then(res => {
		qualityList.value = res.data.records;
	});
	axiosInstance.post('/api/dynamicTableExtension/getPage',
		{ page: 1, pageSize: 999, tableName: 'materialMaintenance' }
	).then(res => {
		const { data, code, message } = res;
		if (code === 200) {
			console.log(data);
			columns.value = data.records;
		}
	});
};
// 新建列
const addColumn = () => {
	if (newColumn.value.tableKey && newColumn.value.tableChineseKey) {
		if (columnDialogTitle.value === '新建') {
			axiosInstance.post('/api/dynamicTableExtension/save', {
				'frontendType': 'INPUT',
				'tableName': 'materialMaintenance',
				'tableKey': newColumn.value.tableKey,
				'tableChineseKey': newColumn.value.tableChineseKey
			}).then(res => {
				if (res.code === 200) {
					ElMessage.success('新建列成功');
					getColumnsList();
					// columns.value.push({ ...newColumn.value });
					newColumn.value = { tableKey: '', tableChineseKey: '', visible: true };
					showAddColumnDialog2.value = false;
				}
			});

		} else {
			console.log('编辑');
			axiosInstance.put('/api/dynamicTableExtension/update', {
				'frontendType': 'INPUT',
				'tableName': 'materialMaintenance',
				'tableKey': newColumn.value.tableKey,
				'tableChineseKey': newColumn.value.tableChineseKey,
				'id': newColumn.value.id

			}).then(res => {
				if (res.code === 200) {
					ElMessage.success('修改成功');
					getColumnsList();
					showAddColumnDialog2.value = false;

				}
			});

		}

	}
};

// 编辑列
const editColumn = (row: any, index: number) => {
	console.log(row);
	columnIndexNumber.value = index;
	columnDialogTitle.value = '编辑';
	showAddColumnDialog2.value = true;
	newColumn.value.tableChineseKey = row.tableChineseKey;
	newColumn.value.tableKey = row.tableKey;
	newColumn.value.id = row.id;

};

// 删除列
const deleteColumn = (row: any, index: number) => {
	axiosInstance.delete('/api/dynamicTableExtension/delete', {
		data: {
			ids: [row.id]
		}
	}).then(res => {
		if (res.code === 200) {
			getColumnsList();
			ElMessage.success('修改成功');

		}
	});
	// columns.value.splice(index, 1);
};
const typeList = ref([
	{ label: '采购入库', value: '0' },
	{ label: '自制入库', value: '1' },
	{ label: '其他', value: '2' }
]);
const isEdit = ref(false);
const showCrud = ref(false);
const crudTitle = computed(() => {
	return isEdit.value ? '编辑' : '新建';
});


// 新建记录
const handleAdd = () => {
	isEdit.value = false;
	formData.value = {};
	showCrud.value = true;
	deputyData.value = [{
		name: null,
		popCount: 0
	}];
};

// 编辑记录
const handleEdit = (row: any) => {
	isEdit.value = true;
	row.materialProperties = row.materialProperties.toString();
	formData.value = { ...row };
	formData.value.qualityPlanIds = formData.value.basedataQualitySchemeList.map(item => item.id);
	if (row.conversionUnit) {
		deputyData.value = JSON.parse(row.conversionUnit);
	}
	showCrud.value = true;
};

// 删除记录
const handleDel = (row: any) => {
	ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning'
	}).then(async () => {
		await deletemateriaL(row.id);
	}).catch(() => {
	});
};


// 保存记录
const handleSave = async () => {
	const formDataObject = columns.value.reduce((acc, col) => {
		acc[col.tableKey] = formData.value[col.tableKey];
		return acc;
	}, {});
	console.log(formDataObject);
	formData.value.extension = formDataObject;
	// if (deputyData.value.length && deputyData.value.length == 0) {
	// 	ElMessage.error('请添加副单位数据');
	// 	return false;
	// }

	// for (const item of deputyData.value) {
	// 	if (!item.name || !item.propCount || item.propCount == 0) {
	// 		ElMessage.error('请输入副单位数据');
	// 		return false;
	// 	}
	// }

	formData.value.conversionUnit = JSON.stringify(deputyData.value);
	let basedataQualitySchemeList = [];
	if (formData.value.qualityPlanIds && formData.value.qualityPlanIds.length > 0) {
		qualityList.value.forEach(item => {
			if (formData.value.qualityPlanIds.includes(item.id)) {
				basedataQualitySchemeList.push(item);
			}
		});
	}
	formData.value.basedataQualitySchemeList = basedataQualitySchemeList;

	// 遍历qualityList.value，检查id是否在formData.value.qualityPlanIds中

	await addmateriaL(formData.value, (() => {
		showCrud.value = false;
	}));
};


</script>
<style scoped>
.editTableView {
	display: flex;
	justify-content: space-between;
}
</style>
